;;; Web page generation for the x10 project

(ns x10.web [:use ring.middleware.params org.mired.bitchin.html
	          [clojure.string :only (join)]
	          [x10.core :only (*devices* set-state)]])

;; Execute the command on the device.
(defn do-command [command device]
  (case command
	"on" (set-state device true)
	"off" (set-state device false)
	(str "Unknown command " command ".")))

(defn write-page [devices display uri response]
  (html (head (title "X10 Controller")
	      (meta_ {:name "viewport" :content "width=160"}))
	(body
	 (h1 "X10 Controller")
	 (p (join " * " (cons
			 (a {:href (format "%shelp.html" uri)} "Help")
			 (for [new-display (keys devices)]
			   (if (= display new-display)
			     (span {:style "font-weight: bold"} display)
			     (a {:href (format "%s?display=%s" uri new-display)}
				new-display))))))
	 (apply table
		(for [device (map second (devices display))]
		  (let [fmt (format "%s?command=%%s&display=%s&what=%s" 
				    uri display (:name device))]
		    (tr (td (a {:href (format fmt "on")} "on"))
			(td {:align "center" :style (case @(:state device)
						      true  "color:green"
						      false "color:red"
						      "color:inherit")} 
			    (:name device))
			(td (a {:href (format fmt "off")} "off"))))))
	 (p response))))


;; The actual app handler
(defn my-handler [req]
  (let [{:strs [command display what] :or {display "Devices"}} (:query-params req)
	result (if-let [device (get-in *devices* [display what])]
		 (do-command command device)
		 (if what (str "Unknown device " what " in " display ".")))]
    {:status 200 
     :headers {"Content-type" "text/html" "Cache-Control" "no-cache"}
     :body (write-page *devices* display (:uri req) result)}))

(def handler (wrap-params my-handler))
